#include "netlib/net/tcp_client.h"
#include "netlib/rpc/rpc_channel_impl.h"

namespace netlib::rpc {

class RpcClient : public NonCopyable {
public:
	RpcClient(net::EventLoop* loop,
	          const net::InetAddress& addr,
	          std::string&& name = "RpcClient") :
	    client_(loop, addr, std::move(name)) {
		client_.SetConnectionCallback(
		    [this](const net::TcpConnectionPtr& conn) { OnConnection(conn); });
		client_.SetMessageCallback([&ch = channel_](const net::TcpConnectionPtr& conn,
		                                            net::Buffer* buf,
		                                            Timestamp ts) { ch.OnMessage(conn, buf, ts); });
	}

	void Connect() { client_.Connect(); }
	bool IsConnected() const { return client_.IsConnected(); }
	auto GetRpcChannel() -> ::google::protobuf::RpcChannel* {
		return dynamic_cast<google::protobuf::RpcChannel*>(&channel_);
	}

private:
	void OnConnection(const net::TcpConnectionPtr& conn) {
		client_.DefaultConnectionCallback(conn);
		if (conn->Connected()) {
			channel_.SetConnection(conn);
		}
	}

private:
	net::TcpClient client_;
	rpc::RpcChannelImpl channel_;
};

} // namespace netlib::rpc